package com.xqkad.myplayer.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;

import com.xqkad.myplayer.fragment.ReceiverFragment;
import com.xqkad.myplayer.service.BroadcastService;
import com.xqkad.myplayer.service.MediaService;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class ReceiverActivity extends LogActivity implements BroadcastService.Actions {
    private Receiver receiver;
    private List<ReceiverFragment> fragments = new ArrayList<ReceiverFragment>();

    public void addReceiverFragment(ReceiverFragment fragment){
        if(fragments.indexOf(fragment) < 0)
            fragments.add(fragment);
    }

    public void removeReceiverFragment(ReceiverFragment fragment){
        fragments.remove(fragment);
    }

    protected void onReceive(final Intent intent){
        for(final ReceiverFragment fragment : fragments){
            if(fragment != null){
                fragment.onReceive(intent);
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        receiver = new Receiver(this);
        registerReceiver(receiver, MediaService.getIntentFilter());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try{
            fragments.clear();
            unregisterReceiver(receiver);
        }catch (Exception e){}
    }

    private final static class Receiver extends BroadcastReceiver{
        private final WeakReference<ReceiverActivity> mReference;

        public Receiver(final ReceiverActivity activity) {
            mReference = new WeakReference<>(activity);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            //Log.d("mytag","receive");
            ReceiverActivity activity = mReference.get();
            if (activity != null){
                activity.onReceive(intent);
            }
        }
    }
}
